<template>
    <div class="mind">
        <NuxtLayout name="default">
            <template #panel>
                <div class="mind-top-blank"></div>
                <div class="p-3">
                    <div class="mb-2 text-[#838a95]">需求描述</div>
                    <el-input
                        v-model="userInput"
                        class="online-demand-font"
                        placeholder="输入你的问题，让 AI 帮你思考并总结。例如：青椒炒肉的做法"
                        type="textarea"
                        :rows="5"
                    />

                    <el-button
                        @click="contentPost"
                        class="w-full my-4"
                        type="primary"
                        :loading="isReceiving"
                        style="
                            background: linear-gradient(
                                to bottom right,
                                var(--el-color-primary),
                                var(--el-color-primary-light-3)
                            );
                        "
                    >
                        生成思维导图内容
                    </el-button>
                    <div class="mb-2 text-[#838a95] flex justify-between">
                        <span>生成内容</span>
                        <span
                            @click="handleStart"
                            class="cursor-pointer"
                            style="color: var(--el-color-primary)"
                        >
                            示例
                        </span>
                    </div>
                    <el-input
                        v-model="result"
                        type="textarea"
                        class="online-demand-result"
                        placeholder="生成内容，也可以自己手动输入生成，使用 Markdown 语法。"
                        :rows="18"
                    />
                    <div class="mt-2">
                        <el-button @click="handleCopy">复制markdown</el-button>
                        <el-button>清空</el-button>
                    </div>

                    <TheGuidedPopup ref="guidedPopupRef" />
                </div>
            </template>
            <div class="bg-white w-full h-full">
                <div class="w-full h-full relative">
                    <!--                    <div-->
                    <!--                        class="font-bold text-[23px] ml-4 leading-10 absolute top-0 left-0 z-10 text-[#838a95]"-->
                    <!--                    >-->
                    <!--                        思维导图-->
                    <!--                    </div>-->
                    <div
                        v-if="!result"
                        class="absolute bg-white w-full h-full flex flex-col items-center justify-center"
                    >
                        <i
                            class="iconfont icon-siweidaotu_huaban1"
                            style="
                                color: var(--el-color-primary);
                                font-size: 60px;
                            "
                        />
                        <div class="font-bold text-[24px]">思维导图</div>
                        <div class="text-[#64748b] text-[16px] my-5">
                            点击下方按钮，开始一个示例
                        </div>
                        <el-button type="primary" @click="handleStart">
                            立即开始
                        </el-button>
                    </div>
                    <div
                        v-if="result"
                        class="absolute flex bottom-[10px] left-[20px]"
                    >
                        <div class="mr-6">
                            <i
                                class="iconfont icon-jiahao cursor-pointer"
                                style="font-size: 20px"
                                @click="handleZoom('+')"
                            />
                        </div>
                        <div class="mr-6">
                            <i
                                class="iconfont icon-jian1 cursor-pointer"
                                style="font-size: 20px"
                                @click="handleZoom('-')"
                            />
                        </div>
                        <div>
                            <i
                                class="iconfont icon-yunduanxiazai cursor-pointer"
                                style="font-size: 20px"
                                @click="handleDownloadImg"
                            />
                        </div>
                    </div>
                    <div class="flex-1 w-full h-full" ref="svgWrapRef">
                        <svg
                            class="flex-1 w-full h-full"
                            ref="svgRef"
                            id="svgRef"
                        />
                    </div>
                </div>
            </div>
        </NuxtLayout>
    </div>
</template>

<script setup lang="ts">
import { getCreationDetail } from '~/api/create'

import { watchThrottled } from '@vueuse/core'

import { ref, onMounted } from 'vue'
import { Transformer } from 'markmap-lib'
import { Markmap } from 'markmap-view'
import { useUserStore } from '~/stores/user'
import { chatSendText } from '~/api/chat'
import { Example_Value, User_Input } from '@/enums/mind'
import feedback from '~/utils/feedback'
import html2Canvas from 'assets/js/html2canvas.esm'
const userStore = useUserStore()
const guidedPopupRef = shallowRef()
const form = ref('')
const transformer = new Transformer()

const svgRef = ref()
const svgWrapRef = ref()
const userInput = ref()
const result = ref('')
const mm = ref()
const zoom = ref(1)
const update = () => {
    const { root } = transformer.transform(result.value)
    mm.value.setData(root)
    mm.value.fit()
}
const handleZoom = (_val) => {
    switch (_val) {
        case '+':
            if (zoom.value > 1) {
                zoom.value += 0.1
            } else {
                zoom.value = 1.1
            }
            break
        case '-':
            if (zoom.value <= 1) {
                zoom.value -= 0.1
            } else {
                zoom.value = 0.9
            }
            break
    }
    mm.value.rescale(zoom.value)
}
const isReceiving = ref(false)
let streamReader: ReadableStreamDefaultReader<Uint8Array> | null = null
const handleStart = () => {
    userInput.value = User_Input
    result.value = Example_Value
}

const handleDownloadImg = async () => {
    try {
        const scale = 1 // 设置缩放比例
        const canvasElement = document.createElement('canvas')

        canvasElement.width = svgWrapRef.value?.clientWidth * scale
        canvasElement.height = svgWrapRef.value?.clientHeight * scale
        // document.body.append(canvasElement)
        const canvas = await html2Canvas(svgWrapRef.value, {
            useCORS: true,
            canvas: canvasElement,
            scale,
            backgroundColor: 'transparent'
        })
        const dataURL = canvas.toDataURL('image/png')
        const aTag = document.createElement('a')
        document.body.appendChild(aTag)
        aTag.href = dataURL
        aTag.download = '图片'
        aTag.click()
    } catch (error) {
        console.log(error)
        feedback.msgError('下载失败，请重试')
    }
}

const contentPost = async () => {
    if (!userStore.isLogin) return userStore.toggleShowLogin(true)
    if (isReceiving.value) return
    if (!userInput.value) {
        ElMessage.error('请输入需求描述')
        return
    }

    result.value = ''
    try {
        await chatSendText(
            {
                model: '',
                question: {
                    [form.value]: userInput.value
                },
                type: 2,
                other_id: 40
            },
            {
                onstart(reader) {
                    streamReader = reader
                },
                onmessage(value) {
                    value
                        .trim()
                        .split('data:')
                        .forEach(async (text) => {
                            if (text !== '') {
                                try {
                                    const dataJson = JSON.parse(text)
                                    const { code, event, data } = dataJson
                                    console.log(data)
                                    if (event == 'error' && code === 101) {
                                        guidedPopupRef.value?.open()
                                    } else if (event == 'error') {
                                        feedback.msgError(data)
                                    }

                                    if (data) {
                                        result.value += data
                                    }
                                } catch (error) {}
                            }
                        })
                },
                onclose() {
                    isReceiving.value = false
                    update()
                }
            }
        )
    } catch (e) {}
}

watchThrottled(
    result,
    () => {
        update()
    },
    { throttle: 500 }
)
const { copy } = useCopy()
const handleCopy = async () => {
    await copy(result.value)
}
onMounted(() => {
    mm.value = Markmap.create(svgRef.value)
    console.log(mm.value)
    getCreationDetail({
        id: 40
    }).then((res) => {
        form.value = res.form[0].id
    })

    // update()
})
</script>

<style scoped lang="scss">
@import 'assets/styles/fix_online_css.scss';
.mind-top-blank {
    min-height: 70px;
    max-height: 140px;
    width: 100%;
    //background: red;
    height: calc(100vh - 800px);
}
//@media screen and (min-height: 600px) {
//    .mind-top-blank {
//        height: 140px;
//    }
//}

h1,
p {
    font-family: Lato;
}
</style>
·
